<template>
  <div>
    <el-form :model="registerForm" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="registerForm.password" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="registerForm.confirmPassword" type="password" show-password />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="registerConfirm">注册</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';

const emit = defineEmits(['register'])

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: ''
})

const registerConfirm = () => {
  if (!registerForm.value.username || !registerForm.value.password) {
    ElMessage.warning('用户名和密码不能为空')
    return
  }

  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    ElMessage.warning('两次密码输入不一致')
    return
  }

  const userInfoStr = JSON.stringify({
    username: registerForm.value.username,
    password: registerForm.value.password
  })

  localStorage.setItem('user', userInfoStr)
  ElMessage.success('注册成功')
  emit('register')
}

const reset = () => {
  registerForm.value = {
    username: '',
    password: '',
    confirmPassword: ''
  }
}
</script>
